<script setup lang="ts">
import {
  addCategory,
  deleteCategory,
  getCategoryByLevel,
  getCategoryDetail,
  getCategoryPage,
  updateCategory,
  updateStatus,
} from "@/api/category";
import {
  AddOrUpdateCategoryParams,
  CategoryPageVO,
  QueryCategoryListParams,
} from "@/api/category/types";
import router from "@/router";
const listLoading = ref(false);
const categoryList = ref<CategoryPageVO[]>();
const dialogVisible = ref(false);
const queryFormRef = ref(ElForm);
const categoryInfoForm = ref(ElForm);
const queryParams = reactive<QueryCategoryListParams>({
  name: "",
  parentId: 0,
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0);
const selectProductCateList = ref<CategoryPageVO[]>([]);
const categoryLevel = ref(1);
const switchLoading = ref(false);
const level = ref(3);
const drawerTitle = computed(() => {
  return addCategoryForm.value.id ? "修改分类" : "添加分类";
});
const showParentId = computed(() => {
  // 如果是修改，不需要显示上级分类
  if (addCategoryForm.value.id) {
    return false;
  }
  // 如果是一级分类，不需要显示上级分类
  return level.value === 1 || level.value === 2;
});
const rules = {
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  parentId: [
    // 当level为3时，parentId不需要校验
    {
      required: level.value !== 3,
      message: "请选择上级分类",
      trigger: "blur",
    },
  ],
  sortOrder: [{ required: true, message: "请输入排序", trigger: "blur" }],
};
const defaultForm = {
  id: undefined,
  name: "",
  parentId: null,
  sortOrder: 1,
  status: 1,
  isParent: 1,
};
const addCategoryForm = ref<AddOrUpdateCategoryParams>(defaultForm);
const btnLoading = ref(false);
/**
 * 数据请求区域
 */
// 分页查询
const handleQuery = () => {
  listLoading.value = true;
  getCategoryPage(queryParams)
    .then((res) => {
      console.log(res.data.list);
      categoryList.value = res.data.list;
      total.value = res.data.total;
    })
    .finally(() => {
      listLoading.value = false;
    });
};

// 更新状态
const handleStatusChange = (row: any) => {
  // 弹出框提示是否更新状态
  ElMessageBox.confirm("确定要修改该分类的状态吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      updateStatus(row.id, row.status).then(() => {
        ElMessage({
          type: "success",
          message: "修改成功",
        });
      });
    })
    .catch(() => {
      row.status === 1 ? (row.status = 0) : (row.status = 1);
    });
};
// 删除分类
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定要删除该分类吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteCategory(row.id).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      });
      handleQuery();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
// 根据级别获取分类
const handleGetCategoryByLevel = () => {
  // 获取分类列表
  getCategoryByLevel(level.value).then((res) => {
    //console.log(res.data);
    selectProductCateList.value = res.data;
  });
};
// 查看下级
const handleShowNextLevel = (row: any) => {
  router.push({ path: "/product/category", query: { parentId: row.id } });
};
const handleUpdate = (row: any) => {
  // 获取分类详情
  getCategoryDetail(row.id).then((res) => {
    addCategoryForm.value = res.data;
    //console.log("addform", addCategoryForm.value);
    //console.log("res", res.data);
    // 如果是二、三级分类，需要设置categoryLevel
    if (res.data.parentId !== 0 && res.data.isParent === 1) {
      categoryLevel.value = 2;
      // 设置上级分类id
      //addCategoryForm.value.parentId = res.data.parentId;
    } else if (res.data.parentId !== 0 && res.data.isParent === 0) {
      categoryLevel.value = 3;
      // 设置上级分类id
      //addCategoryForm.value.parentId = res.data.parentId;
    } else {
      categoryLevel.value = 1;
    }
    dialogVisible.value = true;
  });
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};
// 添加分类
const handleAddCategory = () => {
  btnLoading.value = true;
  if (level.value === 3) {
    addCategoryForm.value.parentId = 0;
  }
  console.log(addCategoryForm.value);
  addCategory(addCategoryForm.value)
    .then(() => {
      ElMessage({
        type: "success",
        message: "添加成功",
      });
      btnLoading.value = false;
      dialogVisible.value = false;
      handleQuery();
      resetForm();
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
// 修改分类
const handleUpdateCategory = () => {
  console.log("addCategoryForm", addCategoryForm.value);
  btnLoading.value = true;
  updateCategory(addCategoryForm.value)
    .then(() => {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      btnLoading.value = false;
      dialogVisible.value = false;
      handleQuery();
      resetForm();
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
// 判断是添加还是修改
const handleAddOrUpdate = () => {
  // 校验表单
  categoryInfoForm.value.validate((valid: any) => {
    if (valid) {
      if (addCategoryForm.value.id) {
        handleUpdateCategory();
      } else {
        handleAddCategory();
      }
    } else {
      return false;
    }
  });
};
// 清空表单
const resetForm = () => {
  categoryInfoForm.value.resetFields();
  addCategoryForm.value = defaultForm;
  categoryLevel.value = 1;
};
const cancelForm = () => {
  resetForm();
  dialogVisible.value = false;
};
const openAddDrawer = () => {
  dialogVisible.value = true;
};

const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
};

// 监听路由变化，重新获取数据
watchEffect(() => {
  router.afterEach(() => {
    // 提取路由参数
    const { query } = router.currentRoute.value;
    if (query.parentId) {
      queryParams.parentId = Number(query.parentId);
    } else {
      queryParams.parentId = 0;
    }
    handleQuery();
  });
});
// 监听categoryLevel变化
watch(categoryLevel, (newVal) => {
  if (newVal === 1) {
    level.value = 3;
    addCategoryForm.value.isParent = 1;
  } else if (newVal === 2) {
    level.value = 1;
    addCategoryForm.value.isParent = 1;
  } else {
    level.value = 2;
    addCategoryForm.value.isParent = 0;
  }
  handleGetCategoryByLevel();
  // 如果是新增时才会清空parentId
  if (!addCategoryForm.value.id) addCategoryForm.value.parentId = null;
});
onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="分类名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><template #icon><i-ep-search /></template>搜索</el-button
          >
          <el-button @click="resetQuery">
            <template #icon><i-ep-refresh /></template>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-row>
          <el-col :xs="24" :sm="18" :lg="22">
            <div style="display: flex; align-items: center">
              <el-icon :size="20"><List /></el-icon>
              <span>数据列表</span>
            </div>
          </el-col>
          <el-col :xs="24" :sm="6" :lg="2">
            <el-button type="success" @click="openAddDrawer">
              <template #icon><i-ep-plus /></template>
              新增</el-button
            >
          </el-col>
        </el-row>
      </template>

      <el-table
        v-loading="listLoading"
        highlight-current-row
        :data="categoryList"
        border
      >
        <el-table-column label="序号" align="center" width="80">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column
          prop="id"
          label="分类编号"
          align="center"
          width="100"
        />
        <el-table-column
          prop="name"
          label="名称"
          align="center"
          min-width="200"
        />
        <el-table-column label="级别" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.parentId === 0" type="success">一级</el-tag>
            <el-tag
              v-else-if="scope.row.parentId !== 0 && scope.row.isParent === 1"
              type="warning"
              >二级</el-tag
            >
            <el-tag
              v-else-if="scope.row.parentId !== 0 && scope.row.isParent === 0"
              type="info"
              >三级</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="是否显示" align="center" width="100">
          <template #default="scope">
            <el-switch
              :loading="switchLoading"
              inline-prompt
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
              v-model="scope.row.status"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="排序"
          align="center"
          width="80"
          prop="sortOrder"
        />
        <!--el-table-column
          label="商品数量"
          align="center"
          width="100"
          prop="productCount"
        /-->
        <el-table-column
          label="创建人"
          align="center"
          width="150"
          prop="createdUser"
        />
        <el-table-column
          label="创建时间"
          align="center"
          width="150"
          prop="createdTime"
        />
        <el-table-column
          label="修改人"
          align="center"
          width="150"
          prop="modifiedUser"
        />
        <el-table-column
          label="修改时间"
          align="center"
          width="150"
          prop="modifiedTime"
        />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              :disabled="scope.row.parentId !== 0 && scope.row.isParent === 0"
              type="info"
              size="small"
              @click="handleShowNextLevel(scope.row)"
              >查看下级</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <el-drawer
      ref="drawerRef"
      v-model="dialogVisible"
      :title="drawerTitle"
      :before-close="handleClose"
      direction="rtl"
      class="demo-drawer"
      size="50%"
    >
      <div class="demo-drawer__content">
        <el-form
          :model="addCategoryForm"
          :rules="rules"
          ref="categoryInfoForm"
          label-width="120px"
          size="default"
        >
          <el-form-item label="分类名称" label-width="100px" prop="name">
            <el-input
              v-model="addCategoryForm.name"
              autocomplete="off"
              maxlength="20"
              minlength="1"
              show-word-limit
              clearable
              placeholder="请输入分类名称"
            />
          </el-form-item>
          <el-form-item label="分类等级" label-width="100px">
            <el-radio-group
              :disabled="addCategoryForm.id !== undefined"
              v-model="categoryLevel"
            >
              <el-radio :label="1">一级</el-radio>
              <el-radio :label="2">二级</el-radio>
              <el-radio :label="3">三级</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-show="showParentId"
            label="上级分类"
            label-width="100px"
            prop="parentId"
          >
            <el-select
              v-model="addCategoryForm.parentId"
              placeholder="请选择分类"
              clearable
            >
              <el-option
                v-for="item in selectProductCateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序" label-width="100px" prop="sortOrder">
            <el-input-number
              v-model="addCategoryForm.sortOrder"
              style="min-width: 240px"
              placeholder="输入正整数"
              :min="1"
              :max="100"
            />
          </el-form-item>
          <el-form-item label="是否显示" label-width="100px" prop="status">
            <el-switch
              v-model="addCategoryForm.status"
              inline-prompt
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
        </el-form>
        <div style=" display: flex; justify-content: center;margin-top: 40px">
          <el-button @click="cancelForm">取消</el-button>
          <el-button
            type="primary"
            :loading="btnLoading"
            @click="handleAddOrUpdate"
            >{{ btnLoading ? "提交中 ..." : "提交" }}</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss"></style>
